package com.hou.netty.serial;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class Server {
    public static void main(String[] args) {
        NioEventLoopGroup wgroup = new NioEventLoopGroup();//管理连接
        NioEventLoopGroup croup = new NioEventLoopGroup();//处理业务
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();//配置
            bootstrap.group(wgroup, croup)
                    .channel(NioServerSocketChannel.class)//指定通道类型
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .handler(new LoggingHandler(LogLevel.INFO))//设置日志输出
                    .childHandler(new ChannelInitializer<SocketChannel>() { //初始化设置
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //设置Marshalling编解码
                            socketChannel.pipeline().addLast(MarshallingCodeFactory.createMarshallingEncoder());
                            socketChannel.pipeline().addLast(MarshallingCodeFactory.createMarshallingDecoder());
                            socketChannel.pipeline().addLast(new ServerHandler());//服务端业务处理
                        }
                    });
            ChannelFuture channelFuture = bootstrap.bind(9527).sync();//同步等待绑定
            channelFuture.channel().closeFuture().sync();//监听同步等待端口关闭
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            wgroup.shutdownGracefully();
            croup.shutdownGracefully();
        }
    }
}
